from django.contrib import admin

from celery_tasks.html.tasks import generate_static_list_search_html, generate_static_sku_detail_html
from . import models


class GoodsCategoryAdmin(admin.ModelAdmin):
    """"商品类别模型管理类"""
    def save_model(self, request, obj, form, change):
        """
        点击保存时调用此方法
        :param request: 保存的请求对象
        :param obj: 保存的模型对象
        :param form: 保存的表单数据
        :param change: 是否保存
        """
        obj.save()
        # 生成商品list详情的静态页面
        generate_static_list_search_html.delay()
        print("aa")

    def delete_model(self, request, obj):
        obj.delete()
        generate_static_list_search_html.delay()


# @admin.register(models.SKU)
class SKUAdmin(admin.ModelAdmin):
    """商品模型站点管理"""
    def save_model(self, request, obj, form, change):
        obj.save()
        generate_static_sku_detail_html.delay(obj.id)

    def delete_model(self, request, obj):
        obj.delete()
        generate_static_sku_detail_html.delay(obj.id)


class SKUImageAdmin(admin.ModelAdmin):
    """商品图片模型站点管理"""
    def save_model(self, request, obj, form, change):
        obj.save()
        # 通过外键获取sku模型对象
        sku = obj.sku
        # 如果当前sku商品还没有默认图片,就给它设置一张默认图片
        if not sku.default_image_url:
            sku.default_image_url = obj.image.url
            generate_static_sku_detail_html.delay(sku.id)

    def delete_model(self, request, obj):
        obj.delete()
        sku = obj.sku
        generate_static_sku_detail_html.delay(sku.id)


# Register your models here.
admin.site.register(models.GoodsCategory, GoodsCategoryAdmin)
admin.site.register(models.GoodsChannel)
admin.site.register(models.Goods)
admin.site.register(models.Brand)
admin.site.register(models.GoodsSpecification)
admin.site.register(models.SpecificationOption)
admin.site.register(models.SKU, SKUAdmin)
admin.site.register(models.SKUSpecification)
admin.site.register(models.SKUImage, SKUImageAdmin)